//
//  RTMKeychain.m
//  RTMKeychain
//
//  Created by Klaas Pieter Annema on 18-03-09.
//  Copyright 2009 Sofa BV. All rights reserved.
//

#import "RTMKeychain.h"


@implementation RTMKeychain

# pragma mark external
- (void)setRTMAccountForUsername: (NSString *)username toPassword:(NSString *)password {
	SecKeychainItemRef rtmKeychainItem = nil;
	
	OSStatus result = SecKeychainAddInternetPassword(NULL, 19, "rememberthemilk.com", 0, NULL, [username length], [username UTF8String], 1, "/", 0,  kSecProtocolTypeHTTPS, kSecAuthenticationTypeHTTPDigest, [password length], [password UTF8String], &rtmKeychainItem);
	
	// Check if the password exists already and modify it if necesary
	if (result == errSecDuplicateItem) {
		UInt32 passwordLength;
		void *passwordBytes;
		
		// Get a reference to the keychain item
		SecKeychainFindInternetPassword(NULL, 19, "rememberthemilk.com", 0, NULL, [username length], [username UTF8String], 1, "/", 0, kSecProtocolTypeHTTPS, kSecAuthenticationTypeHTTPDigest, &passwordLength, &passwordBytes, &rtmKeychainItem);
		
		
		// Update the password
		SecKeychainItemModifyAttributesAndData(rtmKeychainItem, NULL, [password length], [password UTF8String]);
	}
	
	if (rtmKeychainItem != nil)
		CFRelease(rtmKeychainItem);
}

- (NSString *)rtmPasswordForUsername: (NSString *)username {
	UInt32 passwordLength;
	void *passwordBytes;
	
	// Retrieve the password data from the keychain
	SecKeychainFindInternetPassword(NULL, 19, "rememberthemilk.com", 0, NULL, [username length], [username UTF8String], 1, "/", 0, kSecProtocolTypeHTTPS, kSecAuthenticationTypeHTTPDigest, &passwordLength, &passwordBytes, NULL);
	
	NSData *passwordData = [NSData dataWithBytes:passwordBytes length:passwordLength];
	
	// Properly release the password data returned
	SecKeychainItemFreeContent(NULL, passwordBytes);
	
	
	return [[[NSString alloc] initWithData:passwordData encoding:NSUTF8StringEncoding] autorelease];
}

@end
